package com.alipay.app.groupmeal.standard.ui.c.abcp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import com.alibaba.fastjson.JSONObject;
import com.alipay.app.groupmeal.standard.R;
import com.alipay.app.groupmeal.standard.base.BaseMVCActivity;
import com.alipay.app.groupmeal.standard.bean.AliPayResVo;
import com.alipay.app.groupmeal.standard.bean.FoodBean;
import com.alipay.app.groupmeal.standard.bean.SerialPortReceive;
import com.alipay.app.groupmeal.standard.bean.SerialPortSend;
import com.alipay.app.groupmeal.standard.constant.ConfigConstant;
import com.alipay.app.groupmeal.standard.event.EventManager;
import com.alipay.app.groupmeal.standard.http.bean.resp.QrPayModel;
import com.alipay.app.groupmeal.standard.http.bean.resp.Result;
import com.alipay.app.groupmeal.standard.offline.bean.FkBean;
import com.alipay.app.groupmeal.standard.offline.bean.OrderBean;
import com.alipay.app.groupmeal.standard.offline.manager.OrderDataManager;
import com.alipay.app.groupmeal.standard.ui.b.PayingPre;
import com.alipay.app.groupmeal.standard.ui.b.SelectPayResPre;
import com.alipay.app.groupmeal.standard.ui.b.util.NFCManager;
import com.alipay.app.groupmeal.standard.ui.b.util.WIth;
import com.alipay.app.groupmeal.standard.ui.c.SelectPayActivity;
import com.alipay.app.groupmeal.standard.ui.c.pre.PayingMainPre;
import com.alipay.app.groupmeal.standard.ui.c.pre.QrPayResMainPre;
import com.alipay.app.groupmeal.standard.ui.c.pre.ScanQrMainPre;
import com.alipay.app.groupmeal.standard.ui.c.pre.SelectPayMainPre;
import com.alipay.app.groupmeal.standard.util.ByteUtil;
import com.alipay.app.groupmeal.standard.util.SerialPortHelperUtil;
import com.alipay.app.groupmeal.standard.util.USBTransferUtil;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.payment.PaymentAPI;
import com.alipay.sdk.abcphaima.AbcpHM;
import com.alipay.sdk.abcphaima.AbcpHMFree;
import com.alipay.sdk.abcphaima.bean.PageResultData;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Flowable;

import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver;
import top.keepempty.sph.library.SerialPortHelper;

/**
 * 支付中
 */
public class CPayingAbcpActivity2 extends BaseMVCActivity implements NFCManager.OnReceiveNfcTagCallback {

    private PayingPre payingPre;

    private PayingMainPre payingMainPre;

    private QrPayResMainPre qrPayResMainPre;

    private String amount;


    private NFCManager mNFCManager;

    private SelectPayResPre selectPayResPre;


    private String mSessionId;
    private String mTradeNo;

//    public static CPayingAbcpActivity2 payingActivity = null;


//    public static void startActForAbcp(Activity activity, String amount) {
//        //自我启动，带上金额
//        Intent intent = new Intent(activity, CPayingAbcpActivity2.class);
//        intent.putExtra("amount", amount);
//        activity.startActivity(intent);
//    }

    //brainpor
    @Override
    protected int getLayoutId() {
        return R.layout.activity_transparent;
    }

    @Override
    protected void initView() {
//        payingActivity = this;
        mNFCManager = new NFCManager(this);

    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        amount = intent.getStringExtra("amount");
        mTradeNo = "ICZF" + new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.CHINA).format(new Date());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (payingPre != null) {
            payingPre.dismiss();

        }
        if (selectPayResPre != null) {
            selectPayResPre.dismiss();
        }

        payingPre = null;
        selectPayResPre = null;
        amount = null;
        mNFCManager.onDestroy();
        mNFCManager = null;
        mSessionId = null;
        mTradeNo = null;

    }


    @Override
    protected void onPause() {
        super.onPause();
        mNFCManager.cancelDispatch();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mNFCManager.dispatch();
    }

    @Override
    public void initPresentation() {
        super.initPresentation();
        if (mDisplay != null) {
            //副屏显示
            payingPre = new PayingPre(this, mDisplay);
            payingPre.setcPayingAbcpActivity2(CPayingAbcpActivity2.this);
//            registerPresentation(payingPre);
//            showPresentation(payingPre);
            payingPre.show();
            //显示支付中金额
            payingPre.showWaitPay(amount);
        }
        if (mDisplay != null) {
            selectPayResPre = new SelectPayResPre(CPayingAbcpActivity2.this, mDisplay);
            selectPayResPre.setcPayingAbcpActivity2(CPayingAbcpActivity2.this);
//            registerPresentation(selectPayResPre);
        }

        if (mMainDisplay != null) {
            payingMainPre = new PayingMainPre(CPayingAbcpActivity2.this, mMainDisplay);
            payingMainPre.setOwnerActivity(this);
            qrPayResMainPre = new QrPayResMainPre(CPayingAbcpActivity2.this, mMainDisplay);
            qrPayResMainPre.setOwnerActivity(this);

        }
        abcp();
    }

    @Override
    protected void dissmissPresnetation() {
        if (payingMainPre != null) {
            payingMainPre.dismiss();
        }
    }

    @Override
    public boolean onKeyEventBack(KeyEvent event) {
        super.onKeyEventBack(event);
        finish();
        return true;
    }


    private void abcp() {
        //显示支付中金额
        //自由金额模式
        //自由拍照付
        AbcpHMFree.startFreeFace(amount, ConfigConstant.expireTime, new AbcpHM.AbcpScanFaceCallback() {
            @Override
            public void onSuccess(boolean isFace, String authCode, String barCode, String tradeNo, String sessionId, String alipayUid) {
                payingPre.showPaying(amount);
                mSessionId = sessionId;
                if (isFace) {
                    //刷脸返回
                    facePay(isFace, authCode, alipayUid);
                } else {
                    PaymentAPI api = APIManager.getInstance().getPaymentAPI();
                    String terminal_params = api.signWithDelegated(authCode);
                    List<FoodBean> foodBeanList = new LinkedList<>();
                    try {
                        foodBeanList = SerialPortReceive.getInstance().getFoodBeanList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    new WIth(mActivity).qrPayV2(amount, authCode, mSessionId, terminal_params, foodBeanList, new BlockingBaseObserver<Result<AliPayResVo>>() {
                        @Override
                        public void onNext(@NonNull Result<AliPayResVo> stringResult) {
//                            showPresentation(selectPayResPre);
                            selectPayResPre.show();
                            if (stringResult.getResult() == null) {
                                cardError("二维码有误", "showScanFaceOfflinePayResult");
                                selectPayResPre.showError("二维码有误", null);
                                return;
                            }
                            if (stringResult.getResult().isSuccess()) {
                                cardSuccess(stringResult.getResult(), "showScanFaceOfflinePayResult");
                                selectPayResPre.showSuccess(stringResult.getResult().getFk());
                                Flowable.intervalRange(0, 4, 0, 1, TimeUnit.SECONDS)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doOnNext((aLong -> {
                                            String btnText = (4 - aLong) + "秒";
                                        }))
                                        .doOnComplete(CPayingAbcpActivity2.this::finish)
                                        .subscribe();
                            } else {
                                cardError(stringResult.getResult().getMsg(), "showScanFaceOfflinePayResult");
                                selectPayResPre.showError(stringResult.getResult().getMsg(), stringResult.getResult().getFk());
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
//                            if (netRes != null) {
//                                netRes.netRes(null, e);
//                            }
                        }
                    });
                }
            }

            @Override
            public void onFail(String code, String msg) {
                EventBus.getDefault().post(new EventManager.clearAmount());
                System.out.println("触发" + code);

                if ("Z1008".equals(code) || "Z6002".equals(code) || "Z6003".equals(code)) {
                    finish();
                }
                if ("qrCode".equals(code)) {
//                    System.out.println("扫码返回刷脸" + msg);
                    AbcpHMFree.closeFreeFace(mSessionId);
                    toQrPaying(msg);


                }
            }

            @Override
            public void onEvent(String sessionId) {
                mSessionId = sessionId;
            }

        });
    }

    /**
     * 刷脸支付参数
     *
     * @param isFace
     * @param faceToken
     * @param aliUid
     */
    private void facePay(boolean isFace, String faceToken, String aliUid) {
        PaymentAPI api = APIManager.getInstance().getPaymentAPI();
        String terminal_params = api.signWithDelegated(faceToken);
//        if (!onOffLine) {
//            //脱机交易模式
//            FkBean fkBean = FkBeanManager.getInstance().getFkByAliUserId(aliUid);
//            if (fkBean == null) {
//                toResult(isFace ? 0 : 1, faceToken, amount,
//                        mTradeNo, mSessionId, "", false,
//                        0, "1", "查无此人");
//                return;
//
//            } else if (new BigDecimal(amount).compareTo(new BigDecimal(fkBean.getKye())) == -1) {
//                OrderBean orderBean = new OrderBean();
//                orderBean.setSuccess(true);//在线模式，订单为未知状态，则不是成功状态
//                orderBean.setHavePost(false);//在线模式，订单服务器上操作，则表示为上传订单
//                orderBean.setAmount(amount);
//                orderBean.setAuthCode(faceToken);
//                orderBean.setTradeNo(mTradeNo);
//                orderBean.setCreateTime(new Date());
//                orderBean.setCardno(fkBean.getCardno());
//                orderBean.setUserName(fkBean.getName());
//                orderBean.setTerminalParams(terminal_params);
//                OrderDataManager.getInstance().insert(orderBean);
//                toResult(isFace ? 0 : 1, faceToken, amount,
//                        mTradeNo, mSessionId, "", true,
//                        0, "1", "支付成功");
//                System.out.println("isFace：支付成功");
//            } else {
//                toResult(isFace ? 0 : 1, faceToken, amount,
//                        mTradeNo, mSessionId, "", false,
//                        0, "1", "余额不足");
//            }
//            return;
//        }

        OrderBean orderBean = new OrderBean();
        orderBean.setSuccess(false);//在线模式，订单为未知状态，则不是成功状态
        orderBean.setHavePost(true);//在线模式，订单服务器上操作，则表示为上传订单
        orderBean.setAmount(amount);
        orderBean.setAuthCode(faceToken);
        orderBean.setTradeNo(mTradeNo);
        orderBean.setCreateTime(new Date());
        OrderDataManager.getInstance().insert(orderBean);
        List<FoodBean> foodBeanList = new LinkedList<>();
        try {
            foodBeanList = SerialPortReceive.getInstance().getFoodBeanList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        new WIth(this).facePayV2(amount,
                mTradeNo,
                mSessionId,
                faceToken,
                aliUid, terminal_params,
                foodBeanList,
                new BlockingBaseObserver<Result<AliPayResVo>>() {
                    @Override
                    public void onNext(@NonNull Result<AliPayResVo> aliPayResVoResult) {
                        AliPayResVo aliPayResVo = aliPayResVoResult.getResult();
                        System.out.println("正常：" + aliPayResVo.toString());
                        toResult(isFace ? 0 : 1, faceToken, amount,
                                mTradeNo, mSessionId, "", aliPayResVo.isSuccess(),
                                aliPayResVo.getIsFailType(), aliPayResVo.getFailCode(), aliPayResVo.getMsg(),
                                aliPayResVoResult.getResult());
                        if (aliPayResVo.isSuccess()) {
                            //            operateType = "showScanFaceOfflinePayResult";
                            //支付成功订单，需要更改标志，并存入数据库

                            orderBean.setCardno(aliPayResVo.getFk().getCardno());
                            orderBean.setUserName(aliPayResVo.getFk().getName());
                            orderBean.setSuccess(true);
                            OrderDataManager.getInstance().update(orderBean);

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }
                });

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                //TODO  todo somthing here
//                System.out.println("延时启动");
//                wxCheckOrderHandler();
//            }
//        }, 10 * 1000);  //延迟10秒执行
    }

    //
//    /**
//     * 微信查单任务·
//     */
//    private void wxCheckOrderHandler() {
//        EventBus.getDefault().post(new EventManager.clearAmount());
//        finish();
//    }
    private void toResult(int type, final String authCode, String amount,
                          final String tradeNo, final String sessionId, String buyerLogonId,
                          boolean isSuccess, int isFailType, String failCode, String msg, AliPayResVo aliPayResVo) {
        PageResultData pageResultData = new PageResultData();
        pageResultData.success = isSuccess;
        if (isSuccess) {
            pageResultData.buyerLogonId = buyerLogonId;
        } else {
            pageResultData.failCode = failCode;
            pageResultData.message = msg;
        }
        pageResultData.totalAmount = aliPayResVo.getAmount();
        pageResultData.paidAmount = aliPayResVo.getAmount();
        pageResultData.authCode = authCode;
        pageResultData.tradeNo = tradeNo;
        pageResultData.sessionId = sessionId;
        pageResultData.type = type;
        pageResultData.outerExtends = aliPayResVo.getOuterExtends();
        CPayResultAbcpActivity.startAct(CPayingAbcpActivity2.this, pageResultData);
    }

    @Override
    public void onEvent(Object event) {
        super.onEvent(event);
        //查单操作


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mNFCManager.receiveTag(intent);
    }


    /**
     * 刷卡页面
     *
     * @param tag
     */
    @Override
    public void onReceiveNfcTag(String tag) {
        showPage("正在支付", new AbcpHM.AbcpLoadingCallback() {
            @Override
            public void onSuccess(String tradeNo, String sessionId, String alipayUid) {
                List<FoodBean> foodBeanList = new LinkedList<>();
                try {
                    foodBeanList = SerialPortReceive.getInstance().getFoodBeanList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                new WIth(mActivity).cardPayV2(amount, tag, mTradeNo, sessionId, 0, foodBeanList,  new BlockingBaseObserver<Result<AliPayResVo>>() {
                            @Override
                            public void onNext(@NonNull Result<AliPayResVo> stringResult) {
//                                showPresentation(selectPayResPre);
                                selectPayResPre.show();
                                if (stringResult.getResult().isSuccess()) {
                                    SerialPortSend.getInstance().sendData(stringResult.getResult().getFk());
                                    String sendCommand = SerialPortSend.getInstance().getSendCommand();
                                    SerialPortHelper serialPortHelper = SerialPortHelperUtil.getInstance().newSerialPortHelper(mActivity);
                                    serialPortHelper.addCommands(sendCommand.getBytes());
                                    cardSuccess(stringResult.getResult(), "showScanCardOfflinePayResult");
                                    selectPayResPre.showSuccess(stringResult.getResult().getFk());
                                    Flowable.intervalRange(0, 4, 0, 1, TimeUnit.SECONDS)
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .doOnNext((aLong -> {
                                                String btnText = (4 - aLong) + "秒";
                                            }))
                                            .doOnComplete(CPayingAbcpActivity2.this::finish)
                                            .subscribe();
                                } else {
                                    sendFailMsg(tag);
                                    cardError(stringResult.getResult().getMsg(), "showScanCardOfflinePayResult");
                                    selectPayResPre.showError(stringResult.getResult().getMsg(), stringResult.getResult().getFk());
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                sendFailMsg(tag);
                                cardError(e.getMessage(), "showScanCardOfflinePayResult");
                            }
                        });
            }

            @Override
            public void onFail(String code, String msg) {

            }

            @Override
            public void onEvent(String sessionId) {

            }
        });
    }

    public void sendFailMsg(String cardSn) {
        FkBean fk = new FkBean();
        fk.setKye(0);
        fk.setBtye(0);
        fk.setCardsn(cardSn);
        SerialPortSend.getInstance().sendData(fk);
        SerialPortSend.getInstance().setReturnCode("01");
        String sendCommand = SerialPortSend.getInstance().getSendCommand();
        SerialPortHelper serialPortHelper = SerialPortHelperUtil.getInstance().newSerialPortHelper(mActivity);
        serialPortHelper.addCommands(sendCommand.getBytes());
    }

    public void showPage(String msg, AbcpHM.AbcpLoadingCallback callback) {
        if (!AbcpHM.getInstance().isAbcpInitSuccess()) {
            return;
        }
        JSONObject jsonParams = new JSONObject();
        jsonParams.put("cardTag", "MOCK_NFC_TAG");
        AbcpHM.startCanteenBPaaSService(
                "canteen",
                "requestSession",
                jsonParams,
                new BPaaSCallback() {

                    @Override
                    public void onResponse(BPaaSResponse response) {
                        if (response == null || response.getCode() == BPaaSResponse.RESULT_CODE_FAIL) {
                            callback.onFail("", "bpaas服务调用失败");
                        } else if (response.getResult() != null) {
                            Bundle result = response.getResult();
                            Bundle result_result = result.getBundle("result");
                            if (result_result != null) {
                                mSessionId = result_result.getString("sessionId");
                                //mTradeNo = result_result.getString("tradeNo");
                                show(msg, callback);
                            }
                        }


                    }

                    @Override
                    public void onEvent(String s, String s1, Bundle bundle) {

                    }
                });
    }

    /**
     * 拉起等待
     *
     * @param msg
     */
    public void show(String msg, AbcpHM.AbcpLoadingCallback callback) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", mSessionId);
        jsonObject.put("advancedConfig", createAdvancedConfig(msg).toJSONString());

        AbcpHM.startCanteenBPaaSService("payResult", "showCardPayLoadingPage",
                jsonObject, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse bPaaSResponse) {
                    }

                    @Override
                    public void onEvent(String s, String s1, Bundle bundle) {
                        JSONObject jsonObject1 = JSONObject.parseObject(s1);
                        if ("CLOSE".equals(jsonObject1.getString("messageType"))) {
                            callback.onFail("", "超时");
                        }
                        callback.onEvent(mSessionId);
                    }
                });
        callback.onSuccess(mTradeNo, mSessionId, "");
    }

    private static JSONObject createAdvancedConfig(String msg) {
        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");// 表示启用新版本结果页，必须
        JSONObject OuterSummary = new JSONObject();
        OuterSummary.put("title", msg);// 结果页标题，必须
        advancedConfig.put("OuterSummary", OuterSummary);
        return advancedConfig;
    }


    private void cardSuccess(AliPayResVo aliPayResVo, String operateType) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", mSessionId);
        jsonObject.put("tradeNo", mTradeNo);
        jsonObject.put("resultTimeOut", 3);
        jsonObject.put("success", true);

        JSONObject outerSummary = new JSONObject();
        outerSummary.put("enablePaymentVoice", true);
        outerSummary.put("actualAmount", aliPayResVo.getAmount());
        outerSummary.put("title", aliPayResVo.getMsg());
        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");
        advancedConfig.put("OuterSummary", outerSummary);
        advancedConfig.put("OuterExtends", aliPayResVo.getOuterExtends());
        jsonObject.put("advancedConfig", advancedConfig.toJSONString());
        AbcpHM.startCanteenBPaaSService("payResult", operateType,
                jsonObject, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse bPaaSResponse) {

                    }

                    @Override
                    public void onEvent(String s, String s1, Bundle bundle) {

                    }
                });

    }

    /**
     * 扫码结果页 showScanCodeOfflinePayResult
     * 刷卡结果页 showScanCardOfflinePayResult
     *
     * @param msg
     */
    private void cardError(String msg, String operateType) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", mSessionId);
        jsonObject.put("tradeNo", mTradeNo);
        jsonObject.put("resultTimeOut", 3);
        jsonObject.put("success", false);

        JSONObject outerSummary = new JSONObject();
        outerSummary.put("enablePaymentVoice", true);
        outerSummary.put("title", msg);

        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");
        advancedConfig.put("OuterSummary", outerSummary);

        jsonObject.put("advancedConfig", advancedConfig.toJSONString());
        AbcpHM.startCanteenBPaaSService("payResult", operateType,
                jsonObject, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse bPaaSResponse) {

                    }

                    @Override
                    public void onEvent(String s, String s1, Bundle bundle) {

                    }
                });
    }


    private void toQrPaying(String qrCode) {
        //发卡支付
        mActivity.runOnUiThread(() -> {
            showPresentationAtMain(payingMainPre);
            payingMainPre.show();
            payingMainPre.toPay(qrCode);
        });
        PaymentAPI api = APIManager.getInstance().getPaymentAPI();
        String terminal_params = api.signWithDelegated(qrCode);
        List<FoodBean> foodBeanList = new LinkedList<>();
        try {
            foodBeanList = SerialPortReceive.getInstance().getFoodBeanList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        new WIth(mActivity).qrPayV2(amount, qrCode, mSessionId, terminal_params, foodBeanList, new BlockingBaseObserver<Result<AliPayResVo>>() {
            @Override
            public void onNext(@NonNull Result<AliPayResVo> stringResult) {
                System.out.println("成功返回：" + stringResult.toString());

//                qrPayResMainPre.showError(stringResult.getResult());
                showPresentation(selectPayResPre);
                selectPayResPre.show();
                if (stringResult.getResult() == null) {
                    cardError("二维码有误", "showScanFaceOfflinePayResult");
                    selectPayResPre.showError("二维码有误", null);
                    payingMainPre.showError();
                    sendFailMsg("00000000");
                    return;
                }
                if (stringResult.getResult().isSuccess()) {
                    if (stringResult.getResult().getResultCode() != null && "QUERY".equals(stringResult.getResult().getResultCode())) {
                        //需要查单操作
                        payingMainPre.setPayingMsg("正在查询订单状态");
                        order = mSessionId;
                        new Thread(myThread1).start();
                    } else if ("SUCCESS".equals(stringResult.getResult().getResultCode())) {
                        SerialPortSend.getInstance().sendData(stringResult.getResult().getFk());
                        String sendCommand = SerialPortSend.getInstance().getSendCommand();
                        SerialPortHelper serialPortHelper = SerialPortHelperUtil.getInstance().newSerialPortHelper(mActivity);
                        serialPortHelper.addCommands(sendCommand.getBytes());
                        cardSuccess(stringResult.getResult(), "showScanFaceOfflinePayResult");
                        selectPayResPre.showSuccess(stringResult.getResult().getFk());
                        payingMainPre.setPayingMsg("请输入密码");
                        Flowable.intervalRange(0, 4, 0, 1, TimeUnit.SECONDS)
                                .observeOn(AndroidSchedulers.mainThread())
                                .doOnNext((aLong -> {
                                    String btnText = (4 - aLong) + "秒";

                                }))
                                .doOnComplete(() -> finish())
                                .subscribe();
//                        selectPayResPre.showError("支付成功", stringResult.getResult().getFk());
                        payingMainPre.showSuccess(stringResult.getResult().getFk());
                    }
                } else {
                    sendFailMsg("00000000");
                    cardError(stringResult.getResult().getMsg(), "showScanFaceOfflinePayResult");
                    selectPayResPre.showError(stringResult.getResult().getMsg(), stringResult.getResult().getFk());
                    payingMainPre.showError();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
//                qrPayResMainPre.show();
//                qrPayResMainPre.showError(e.getMessage());
                sendFailMsg("00000000");
                payingMainPre.showError();
            }
        });
    }

    String order;
    MyThread1 myThread1 = new MyThread1();

    private class MyThread1 extends Thread {

        //在run方法里复写需要进行的操作:卖票速度1s/张
        @Override
        public void run() {
            try {
                sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }


            new WIth(mActivity).checkOrder(order, new BlockingBaseObserver<Result<JSONObject>>() {
                @Override
                public void onNext(@NonNull Result<JSONObject> qrPayModelResult) {
                    System.out.println("查单结果");
                    String state = qrPayModelResult.getResult().getString("state");
                    if ("SUCCESS".equals(state)) {
                        //支付成功
                        FkBean fkBean = qrPayModelResult.getResult().getJSONObject("fk").toJavaObject(FkBean.class);
                        SerialPortSend.getInstance().sendData(fkBean);
                        String sendCommand = SerialPortSend.getInstance().getSendCommand();
                        SerialPortHelper serialPortHelper = SerialPortHelperUtil.getInstance().newSerialPortHelper(mActivity);
                        serialPortHelper.addCommands(sendCommand.getBytes());
                        selectPayResPre.showSuccess(fkBean);
                        Flowable.intervalRange(0, 4, 0, 1, TimeUnit.SECONDS)
                                .observeOn(AndroidSchedulers.mainThread())
                                .doOnNext((aLong -> {
                                    String btnText = (4 - aLong) + "秒";

                                }))
                                .doOnComplete(() -> finish())
                                .subscribe();
                        payingMainPre.showSuccess(fkBean);

                    } else if ("USERPAYING".equals(state)) {
                        mActivity.runOnUiThread(() -> {
                            payingMainPre.setPayingMsg("请输入密码");
                            selectPayResPre.showError("请输入密码", null);
                        });

                        new Thread(myThread1).start();
                    } else if ("ERROR".equals(state)) {
                        mActivity.runOnUiThread(() -> {
                            sendFailMsg("00000000");
                            payingMainPre.setPayingMsg("支付失败");
                            selectPayResPre.showError("支付失败", null);
                        });


                    }

                }

                @Override
                public void onError(@NonNull Throwable e) {
                    sendFailMsg("00000000");
                    System.out.println("系统报错");
                    payingMainPre.setPayingMsg("系统报错");
                    selectPayResPre.showError("系统报错", null);
                }
            });

        }
    }


}
